/*
 * Filename: MainActivity.java
 * Description: This class is for the first activity running in this application.
 */

package edu.usc.libtalk;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Window;
import android.widget.ProgressBar;
import edu.usc.libtalk.task.GetJSONObjectTask;
import edu.usc.libtalk.utils.ApplicationService;
import edu.usc.libtalk.utils.InternalConstant;

public class MainActivity extends Activity implements InternalConstant  {
	private ProgressBar mProgress;
	Intent intent;
	private String deviceID;
	private static final String TAG = "MainActivity";
	public static Activity mainActivity;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Customize menu title 
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        
        setContentView(R.layout.activity_main);

        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title_no_buttons);
        
        mainActivity = this;        
		
		// Get device ID
		deviceID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		ApplicationService.setDeviceID(deviceID);		
		
		// Connect to the server
        mProgress = (ProgressBar) findViewById(R.id.logo_progressBar);
        startConnection();         
        
    }

    private void startConnection(){
    	
    	intent = new Intent(MainActivity.this, LibListActivity.class);
    	
    	// Register the user with default name    	
    	new GetJSONObjectTask(){
    		@Override
    		protected void onPostExecute(JSONObject result){
				if(result == null){
					ApplicationService.inform(getString(R.string.nointernet));
					finish();
					return;
				}         		
				
				// Parse JSON Object				
                try{
                	String authen = result.getString("result");
                	
                	if((authen.length() != 0) && authen.equals("Success"))
                	{
                		Thread.sleep(1000);
                		startActivity(intent);
                	}else {
                		ApplicationService.inform("Connection errored");
    					finish();
    					return;                		
                	}
                	
                	
                }
                catch(JSONException e){
                	Log.e(TAG, "Error parsing data "+e.toString());
                } catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}         		
         	}	
        }.withProgressBar(mProgress, 30).execute(HOSTNAME + CHECK_DB_URL);	
    }    
    
    protected void onResume() {
    	super.onResume();
    }
    
    protected void onPause() {
    	super.onPause();
    }
    
}
